/**
 * Copyright (c) 2010 Jesco Freund.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of Backtory nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $Id$
 */

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "config.h"
#include "backtoryd.h"
#include "message.h"


int
handle_signal(int sig_no, _daemon_sighandler_t signalhandler)
{
	struct sigaction action;
	
	action.sa_handler = signalhandler;
	sigemptyset(&action.sa_mask);
	action.sa_flags = 0;
	
	if (sigaction(sig_no, &action, NULL) < 0)
		return 1;
	
	return 0;
}

extern int
daemonize(msg_ctx_t *ctx_old, msg_ctx_t *ctx_new, const char *pidfile)
{
	pid_t pid;
	FILE *pid_fp;
	int sigs[] = { SIGHUP, SIGINT, SIGQUIT, SIGTSTP, SIGTTIN, SIGTTOU };
	int i;
	
	for (i = 0; i < sizeof(sigs) / sizeof(int); i++)
	{
		if (0 != handle_signal(sigs[i], SIG_IGN))
		{
			msg_log(ctx_old, LOG_ERR, "Error %d in sigaction: %s\n", errno, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}
	
	switch (pid = fork())
	{
		case -1:
			msg_log(ctx_old, LOG_ERR, "Error %d in fork: %s\n", errno, strerror(errno));
			exit(EXIT_FAILURE);
			break;
		case 0:
			break;
		default:
			exit(EXIT_SUCCESS);
			break;
	}
	
	if (0 > setsid())
	{
		msg_log(ctx_new, LOG_ERR, "Error %d in setsid: %s\n", errno, strerror(errno));
		exit(EXIT_FAILURE);
	}
	
	switch (pid = fork())
	{
		case -1:
			msg_log(ctx_new, LOG_ERR, "Error %d in fork: %s\n", errno, strerror(errno));
			exit(EXIT_FAILURE);
			break;
		case 0:
			break;
		default:
			exit(EXIT_SUCCESS);
			break;
	}
	
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);
	
	chdir("/");
	umask(0);
	
	if (NULL != pidfile)
	{
		pid_fp = fopen(pidfile, "w");
		if (NULL == pid_fp)
		{
			msg_log(ctx_new, LOG_ERR, "Error %d in fopen: %s\n", errno, strerror(errno));
			exit(EXIT_FAILURE);
		}
		fprintf(pid_fp, "%d", (int)getpid());
		fclose(pid_fp);
	}
	
	return 0;
}
